<?php
/**
 * 功能说明：抽奖类
 * 参数说明：
 * 返回值：
 * 备注说明：
 * 作者：Administrator
 * 最后一次修改时间:2017/5/14 17:14
 */

namespace logic\luckydraw;

use logic\LogicException;
use logic\luckydraw\PrizePoll;

class PrizeTurn
{
	//奖池
	protected $poll = null;

	public function __construct( PrizePoll $poll )
	{
		if ( $poll ) {
			$this -> setPoll( $poll );
		}
	}

	//抽奖

	public function run( PrizePoll $poll = null )
	{
		$poll = $poll ? $poll : $this -> poll;
		if ( !$poll ) {
			throw new LogicException( 1 );
		}

		if ( $poll -> count() <= 0 ) {
			throw new LogicException( 2 );
		}

		$items = $poll -> getVisibleItems();
		if ( count( $items ) <= 0 ) {
			throw new LogicException( 3 );
		}

		$sum = 0;
		foreach ( $items as $item ) {
			$start = $sum + 1;
			$sum += $item -> getWeight();
			$end = $sum;
			//设置奖品的权重范围区间
			$item -> setRange( $start , $end );
		}

		//随机数
		$rand = $this -> getRandNum( 1 , $sum );
		//echo "总数：{$sum}，随机出数:{$rand}      ";

		//区间段判断
		foreach ( $items as $item ) {
			if ( $item -> inRange( $rand ) ) {
				return $item;
			}
		}
		return null;
	}

	//获取随机数
	public function getRandNum( $min , $max )
	{
		return mt_rand( $min ? $min : 1 , $max );
	}

	//设置奖池
	public function setPoll( PrizePoll $poll )
	{
		$this -> poll = $poll;
	}
}